package yagwl.client.view.demo;

import yagwl.client.model.ItemDTO;
import yagwl.client.model.demo.ProductListCache;
import yagwl.client.resource.Resources;
import yagwl.client.widget.AbstractSelectItemDialogBox;
import yagwl.client.widget.PagedFlexTable.Action;
import yagwl.client.widget.PagedFlexTable.RowActionCallback;

import com.google.gwt.user.client.ui.Image;

public class SelectProductDialogBox extends AbstractSelectItemDialogBox {

  private final ProductListCache listCache;

  public SelectProductDialogBox(ProductListCache listCache) {
    super(listCache);
    this.listCache = listCache;
    setText("Select Product");
    table.addColumn(Column.Name.ordinal(), "Name");
    table.addColumn(Column.ImageUrl.ordinal(), "Image");
    table.addColumn(Column.Description.ordinal(), "Description", "100px");
    table.addColumn(Column.Price.ordinal(), "Price");
    table.enableRowSelect();
    table.setRowActionCallback(new ProductRowActionCallback());

    table.renderUI();
    setWidget(table);
  }

  private class ProductRowActionCallback implements RowActionCallback {

    @Override
    public void action(Action action, int dataRowIdx, int objIdx) {
      ItemDTO prd = (ItemDTO) listCache.getList().get(objIdx);
      switch (action) {
      case Populate:
        table.setCellText(dataRowIdx, Column.Name.ordinal(), prd.get("name"));
        if (prd.get("imageUrl") != null && !prd.get("imageUrl").equals(""))
          table.setCellWidget(dataRowIdx, Column.ImageUrl.ordinal(),
              new Image(prd.get("imageUrl")));
        else { // clear out previous photo
          // there seems to be a bug, clearCell isnt working always
          // rootTP.clearCell(tableRow, Photo);
          table.setCellWidget(dataRowIdx, Column.ImageUrl.ordinal(),
              new Image(Resources.I.trpx()));
        }
        table.setCellText(dataRowIdx, Column.Description.ordinal(), prd
            .get("description"));
        table.setCellText(dataRowIdx, Column.Price.ordinal(), prd
            .get("priceStr"));
        break;
      case Select:
        setSelectedListItem(prd);
        SelectProductDialogBox.this.hide();
        break;
      }
    }
  }

  private enum Column {
    Name, ImageUrl, Description, Price
  }

}
